package com.socket.nio.nio.pipeline;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Hexudong
 * @date 2025/4/12
 */
@Slf4j
public class TestPipeline {
  public static void main(String[] args) {
    new ServerBootstrap()
        .group(new NioEventLoopGroup())
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<NioSocketChannel>() {

          @Override
          protected void initChannel(NioSocketChannel ch) {
            ChannelPipeline pipeline = ch.pipeline();
            // 添加处理器 head -> h1 -> h2 ->  h3->  h4->  h5-> h6 -> tail

            // 添加入栈处理器，h1 h2 h3 从head开始处理
            pipeline.addLast("h1", new ChannelInboundHandlerAdapter() {
              @Override
              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.debug("读取数据 [1]");
                super.channelRead(ctx, msg);
              }
            });
            pipeline.addLast("h2", new ChannelInboundHandlerAdapter() {
              @Override
              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.debug("读取数据 [2]");
                super.channelRead(ctx, msg);
              }
            });
            pipeline.addLast("h3", new ChannelInboundHandlerAdapter() {
              @Override
              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.debug("读取数据 [3]");
                super.channelRead(ctx, msg);
                ch.writeAndFlush(ctx.alloc().buffer().writeBytes("hello, world".getBytes()));
              }
            });

            // 添加出栈处理器，h4 h5 h6 从tail开始处理
            pipeline.addLast("h4", new ChannelOutboundHandlerAdapter() {
              @Override
              public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.debug("读取数据 [4]");
                super.write(ctx, msg, promise);
              }
            });
            pipeline.addLast("5", new ChannelOutboundHandlerAdapter() {
              @Override
              public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.debug("读取数据 [5]");
                super.write(ctx, msg, promise);
              }
            });
            pipeline.addLast("h6", new ChannelOutboundHandlerAdapter() {
              @Override
              public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.debug("读取数据 [6]");
                super.write(ctx, msg, promise);
              }
            });
          }
        })
        .bind(8082);
  }
}
